package com.spiderette.ace.sdk.utils;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class SAceAesUtils {

    public static String encrypt(String plainText, String key) {
        try {
            // 硬编码 IV（16 字节）
            byte[] iv = "1234567890123456".getBytes(); // 示例 IV，必须是 16 字节

            byte[] keyBytes = android.util.Base64.decode(key, Base64.DEFAULT);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);

            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());

            // 直接返回密文（不再需要拼接 IV）
            return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String decrypt(String encryptedText, String key) {
        try {
            // 硬编码 IV（16 字节，必须与加密时一致）
            byte[] iv = "1234567890123456".getBytes();

            byte[] encryptedBytes = Base64.decode(encryptedText, Base64.DEFAULT);

            byte[] keyBytes = Base64.decode(key, Base64.DEFAULT);
            SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

            byte[] originalBytes = cipher.doFinal(encryptedBytes);
            return new String(originalBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
